package com.gofaraway.service.student.leetcode;

import java.util.List;

/**
 * @author ChenPeng
 * @Date 2024/6/29 17:18
 */
public class Demo07 {


    /**
     * 删除链表的倒数第n个节点
     * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
     *
     * @param head
     * @param n
     * @return
     */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        //设置一个哑节点
        ListNode dummy = new ListNode(0, head);
        //遍历获取 链表长度
        int length = getLength(head);

        ListNode curr = dummy;
        for (int i = 1; i < length - n + 1; i++) {
            curr = curr.next;
        }
        curr.next = curr.next.next;
        ListNode ans = dummy.next;
        return ans;

    }

    private int getLength(ListNode head) {
        int length = 0;
        while (head != null) {
            length++;
            head = head.next;
        }
        return length;
    }

}
